<script>
import ProcessDesigner from '@/components/ProcessDesigner/index.vue'
import { getModel, updateModel } from '@/api/bpm/model'

export default {
  name: 'ModelDesign',
  components: { ProcessDesigner },
  data() {
    return {
      designerOpen: true,
      designerData: {
        loading: false,
        bpmnXml: '',
        form: {
          name: '',
          key: '',
          description: ''
        }
      },
      xmlString: '',
      modelKey: '',
      modelName: '',
      // 流程模型的信息
      modelData: {}
    }
  },
  mounted() {
    const { modelId } = this.$route.query
    this.getModelById(modelId)
  },
  methods: {
    onSaveDesigner(bpmnXml) {
      console.log('bpmnXml:', bpmnXml)
      const data = {
        ...this.modelData, bpmnXml: bpmnXml
      }
      if (data.id) {
        updateModel(data).then(() => {
          this.loading = false
          this.$message.success('修改成功')
          this.$router.back()
        })
      } else {
        this.$message.error('保存失败，未找到对应流程模型，请先创建流程模型！')
      }
    },
    getModelById(modelId) {
      getModel(modelId).then(response => {
        this.loading = false
        this.xmlString = response.data.bpmnXml || null
        this.modelKey = response.data.key
        this.modelName = response.data.name
        this.modelData = {
          ...response.data,
          bpmnXml: this.xmlString // 清空 bpmnXml 属性
        }
        this.$refs.modelDesigner.onCreateBpmn(this.xmlString, this.modelKey, this.modelName)
      })
    }
  }
}
</script>

<template>
  <process-designer
    :key="designerOpen"
    ref="modelDesigner"
    v-loading="designerData.loading"
    style="border:1px solid rgba(0, 0, 0, 0.1);"
    :bpmn-xml="xmlString"
    :designer-form="modelData"
    @save="onSaveDesigner"
  />
</template>

<style scoped lang="scss">

</style>
